package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.GoodsPartDetailDto;
import com.tticar.invmanager.entity.vo.GoodsPartDto;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.mapper.GoodsPartMapper;
import com.tticar.invmanager.service.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-10-15
 */
@Service
public class GoodsPartServiceImpl extends ServiceImpl<GoodsPartMapper, GoodsPart> implements IGoodsPartService {

    @Autowired
    private ICodeCounterService codeCounterService;

    @Autowired
    private IGoodsPartDetailService goodsPartDetailService;

    @Autowired
    private IRepositoryCountService repositoryCountService;

    @Autowired
    private IInRepositoryDetailService repositoryDetailService;

    @Autowired
    private IOutRepositoryDetailService outRepositoryDetailService;

    @Autowired
    private IInRepositoryDetailService inRepositoryDetailService;

    @Autowired
    private IMMaterielSkuService materielSkuService;

    @Autowired
    private IWPositionMaterielService positionMaterielService;

    @Override
    public Page selectPage(GoodsPart goodsPart, MyPage<GoodsPart> page) {
        return  page.setRecords(this.baseMapper.search(goodsPart, page));
    }
    @Override
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            GoodsPart goodsPart = new GoodsPart();
            goodsPart.setId(id);
            goodsPart.setStatus(-1);
            list.add(goodsPart);
        }
        this.updateBatchById(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addGoodsPart(GoodsPartDto dto) {
        GoodsPartDetailDto goodsFrom = dto.getFrom();
        List<GoodsPartDetailDto> goodsToList = dto.getList();

        GoodsPart part = new GoodsPart();
        Date now = DateUtil.StringToDate(dto.getOrderTime() + " " + DateUtil.DateToString(new Date(), DateStyle.HH_MM_SS));
        part.setOrderTime(now);
        part.setCode(codeCounterService.getOrderCode(CodeType.CZ));
        part.setWearhouseId(dto.getHouseId());
        part.setBatchCode(goodsFrom.getHouse());
        part.setSkuId(goodsFrom.getSkuId());
        part.setPrice(goodsFrom.getPrice());
        part.setNum(goodsFrom.getNum());
        part.setFee(goodsFrom.getFee());
        part.setRemark(dto.getRemark());
        part.setCtime(now);
        part.setCname(MySecurityUtils.currentUser().getUsername());
        this.baseMapper.insert(part);

        for(GoodsPartDetailDto tmp : goodsToList) {
            GoodsPartDetail detail = new GoodsPartDetail();
            detail.setPartId(part.getId());
            detail.setWearhouseId(part.getWearhouseId());
            detail.setPositionId(tmp.getPositionId());
            detail.setSkuId(tmp.getSkuId());
            detail.setNum(tmp.getNum());
            detail.setPrice(tmp.getPrice());
            detail.setFee(tmp.getFee());
            this.goodsPartDetailService.insert(detail);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editGoodsPart(GoodsPartDto dto) {
        GoodsPartDetailDto goodsFrom = dto.getFrom();
        List<GoodsPartDetailDto> goodsToList = dto.getList();

        GoodsPart part = this.baseMapper.selectById(dto.getId());

        part.setBatchCode(goodsFrom.getHouse());
        part.setPrice(goodsFrom.getPrice());
        part.setNum(goodsFrom.getNum());
        part.setFee(goodsFrom.getFee());
        part.setRemark(dto.getRemark());

        if(dto.getType() == 1) {//审核
            part.setOname(MySecurityUtils.currentUser().getUsername());
            part.setOtime(new Date());
            part.setStatus(1);

            //出库校验
            String house = goodsFrom.getHouse();
            for(String tmp : house.split(",")) {
                String[] arr = tmp.split("_");
                Long positionId = Long.valueOf(arr[2]);
                String batchCode = arr[4];
                Integer num = Integer.valueOf(arr[6]);

                Long nowNum = this.repositoryDetailService.getSkuNumByBatchCode(part.getSkuId(), batchCode);
                if(nowNum < num) {
                    throw new MyServiceException("被拆装商品无有效库存，请重新选择库存");
                }

                //生成出库单
                OutRepositoryDetail outDetail = new OutRepositoryDetail();
                outDetail.setSkuId(part.getSkuId());
                outDetail.setCode(codeCounterService.getOrderCode(CodeType.CK));
                outDetail.setBuszId(part.getId());
                outDetail.setBatchNumber(batchCode);
                outDetail.setWearhouseId(part.getWearhouseId());
                outDetail.setPositionId(positionId);
                outDetail.setOrderTime(part.getOrderTime());
                outDetail.setType(2);//拆装出库
                outDetail.setCount(num);
                outDetail.setRemark("");
                outDetail.setStatus(0);
                outDetail.setCtime(new Date());
                outDetail.setUsername(MySecurityUtils.currentUser().getUsername());
                this.outRepositoryDetailService.insert(outDetail);

                repositoryCountService.updateRepositoryCount(outDetail.getSkuId(), outDetail.getWearhouseId(),  outDetail.getCount() * -1);
            }
        }
        this.baseMapper.updateById(part);

        String rkCode = dto.getType() == 1 ? codeCounterService.getOrderCode(CodeType.RK) : "";
        for(GoodsPartDetailDto tmp : goodsToList) {
            GoodsPartDetail detail = this.goodsPartDetailService.selectById(tmp.getId());
            detail.setPositionId(tmp.getPositionId());
            detail.setNum(tmp.getNum());
            detail.setPrice(tmp.getPrice());
            detail.setFee(tmp.getFee());
            this.goodsPartDetailService.updateById(detail);

            if(dto.getType() == 1) {//审核
                //入库校验 当前仓库是否仍绑定了此商品
                MMaterielSku sku = this.materielSkuService.selectById(detail.getSkuId());
                int isExsit = this.positionMaterielService.selectCount(new EntityWrapper().eq("materiel_id", sku.getMid()).eq("position_id", detail.getPositionId()));
                if(isExsit == 0) {
                    throw new MyServiceException(sku.getCode() + "库位无效，请重新选择");
                }

                //生成入库单
                InRepositoryDetail inDetail = new InRepositoryDetail();
                inDetail.setSkuId(detail.getSkuId());
                inDetail.setCode(rkCode);
                inDetail.setBuszId(detail.getId());
                inDetail.setBatchNumber(codeCounterService.getBatchCode());
                inDetail.setWearhouseId(detail.getWearhouseId());
                inDetail.setPositionId(detail.getPositionId());
                inDetail.setOrderTime(part.getOrderTime());
                inDetail.setType(2);//拆装入库
                inDetail.setCount(detail.getNum());
                inDetail.setStatus(0);
                inDetail.setCtime(new Date());
                inDetail.setUsername(MySecurityUtils.currentUser().getUsername());
                inRepositoryDetailService.insertOrUpdate(inDetail);

                repositoryCountService.updateRepositoryCount(detail.getSkuId(), inDetail.getWearhouseId(),inDetail.getCount());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(Long id) {
        GoodsPart part = this.baseMapper.selectById(id);

        part.setOname(MySecurityUtils.currentUser().getUsername());
        part.setOtime(new Date());
        part.setStatus(1);
        this.baseMapper.updateById(part);

        //出库校验
        String house = part.getBatchCode();
        Integer count = part.getNum();
        List<RepositoryCount> repositoryCounts = repositoryCountService.queryOutRepository(part.getSkuId());
        if (repositoryCounts != null && repositoryCounts.size() > 0) {
            for (RepositoryCount rep : repositoryCounts) {


                Long wearhouseId = rep.getWearhouseId();

                Integer num = Integer.valueOf(rep.getCount() > count ? count : rep.getCount());

                OutRepositoryDetail outDetail = new OutRepositoryDetail();
                outDetail.setSkuId(part.getSkuId());
                outDetail.setCode(codeCounterService.getOrderCode(CodeType.CK));
                outDetail.setBuszId(part.getId());
                outDetail.setWearhouseId(part.getWearhouseId());
                outDetail.setOrderTime(part.getOrderTime());
                outDetail.setType(2);//拆装出库
                outDetail.setCount(num);
                outDetail.setRemark("");
                outDetail.setStatus(0);
                outDetail.setCtime(new Date());
                outDetail.setUsername(MySecurityUtils.currentUser().getUsername());
                this.outRepositoryDetailService.insert(outDetail);

                repositoryCountService.updateRepositoryCount(part.getSkuId(), wearhouseId, num * -1);

                count = count - rep.getCount();
                if (count <= 0) {
                    break;
                }

            }
        } else {
            throw new MyServiceException("库存不足");
        }
//        for(String tmp : house.split(",")) {
//            String[] arr = tmp.split("_");
//            Long positionId = Long.valueOf(arr[2]);
//            String batchCode = arr[4];
//            Integer num = Integer.valueOf(arr[6]);
//
//            Long nowNum = this.repositoryDetailService.getSkuNumByBatchCode(part.getSkuId(), batchCode);
//            if(nowNum < num) {
//                throw new MyServiceException("被拆装商品无有效库存，请重新选择库存");
//            }
//
//            //生成出库单
//            OutRepositoryDetail outDetail = new OutRepositoryDetail();
//            outDetail.setSkuId(part.getSkuId());
//            outDetail.setCode(codeCounterService.getOrderCode(CodeType.CK));
//            outDetail.setBuszId(part.getId());
//            outDetail.setBatchNumber(batchCode);
//            outDetail.setWearhouseId(part.getWearhouseId());
//            outDetail.setPositionId(positionId);
//            outDetail.setOrderTime(part.getOrderTime());
//            outDetail.setType(2);//拆装出库
//            outDetail.setCount(num);
//            outDetail.setRemark("");
//            outDetail.setStatus(0);
//            outDetail.setCtime(new Date());
//            outDetail.setUsername(MySecurityUtils.currentUser().getUsername());
//            this.outRepositoryDetailService.insert(outDetail);
//
//            repositoryCountService.updateRepositoryCountByPositionId(outDetail.getSkuId(), outDetail.getWearhouseId(), outDetail.getPositionId(), outDetail.getCount() * -1);
//        }


        String rkCode = codeCounterService.getOrderCode(CodeType.RK);
        List<GoodsPartDetail> list = this.goodsPartDetailService.selectList(new EntityWrapper().eq("part_id", id));
        for(GoodsPartDetail detail : list) {
            //入库校验 当前仓库是否仍绑定了此商品
            MMaterielSku sku = this.materielSkuService.selectById(detail.getSkuId());
            int isExsit = this.positionMaterielService.selectCount(new EntityWrapper().eq("materiel_id", sku.getMid()).eq("position_id", detail.getPositionId()));
            if(isExsit == 0) {
                throw new MyServiceException(sku.getCode() + "库位无效，请重新选择");
            }

            //生成入库单
            InRepositoryDetail inDetail = new InRepositoryDetail();
            inDetail.setSkuId(detail.getSkuId());
            inDetail.setCode(rkCode);
            inDetail.setBuszId(detail.getId());
            inDetail.setBatchNumber(codeCounterService.getBatchCode());
            inDetail.setWearhouseId(detail.getWearhouseId());
            inDetail.setPositionId(detail.getPositionId());
            inDetail.setOrderTime(part.getOrderTime());
            inDetail.setType(2);//拆装入库
            inDetail.setCount(detail.getNum());
            inDetail.setStatus(0);
            inDetail.setCtime(new Date());
            inDetail.setUsername(MySecurityUtils.currentUser().getUsername());
            inRepositoryDetailService.insertOrUpdate(inDetail);

            repositoryCountService.updateRepositoryCount(detail.getSkuId(), inDetail.getWearhouseId(), inDetail.getCount());
        }
    }

    @Override
    public List<Map> getInfo(Long id) {
        List<Map> list = new ArrayList<>();
        Map<String, Object> map = this.baseMapper.getInfo(id);
        GoodsPart part = this.baseMapper.selectById(id);
        map.put("num", part.getNum());
        map.put("fee", part.getFee());
        map.put("price", part.getPrice());//需求说变动不管
        map.put("house", part.getBatchCode());
        //最新库存
        List<Map> skuList = repositoryCountService.getSkuNumByHouseId(part.getSkuId() + "", part.getWearhouseId());
        if(skuList.size() > 0) {
            map.put("skusNum", skuList.get(0).get("skuNum"));
        }
        list.add(map);
        return list;
    }
}
